package config;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
import org.apache.log4j.Logger;

public class FlatFileLoaders
{
    // Logger
    private static Logger myLogger = Logger.getLogger(FlatFileLoaders.class.getName());
    
    // Flat file names
    private static String propertiesFlatFile = "sms-attendance.properties";
    
    /**
     * Loads information from that database and stores in the information
     * 
     */
    public static void loadSystemProperties()
    {
	String propertiesFlatFilePath = pathAppenders(getConfigFlatFileDirectory(), propertiesFlatFile, false);

	FileReader fr;
	try
	{
	    myLogger.info("Trying to load properties from: " + propertiesFlatFilePath);
	    fr = new FileReader(propertiesFlatFilePath);
	    try
	    {
		Properties prop = new Properties();
		prop.load(fr);
		
		// Run Mode
		ConfigData.isTestMode=Boolean.parseBoolean(prop.getProperty("mode.test"));
		
		// Delays and waits
		ConfigData.monitorRate=Integer.parseInt(prop.getProperty("rate.inbox.monitor"));
		ConfigData.threadJoinWait=Integer.parseInt(prop.getProperty("wait.thread"));
		
		
		// Database
		ConfigData.dbHost=prop.getProperty("db.host");
		ConfigData.dbName=prop.getProperty("db.name");
		ConfigData.dbUserName=prop.getProperty("db.username");
		ConfigData.dbPassword=prop.getProperty("db.password");
	    }
	    finally
	    {
		try
		{
		    fr.close();
		}
		catch (IOException e)
		{
		    myLogger.error("Could not close the properties file.", e);
		}
	    }
	}
	catch (FileNotFoundException e)
	{
	    myLogger.error("Could not find file: " + propertiesFlatFilePath, e);
	}
	catch (IOException e)
	{
	    myLogger.error("Could not read from file: " + propertiesFlatFilePath, e);
	}
    }
    
    /**
     * Modify this function so that other functions know where to look for flat files
     * 
     * @return
     */
    public static String getConfigFlatFileDirectory()
    {
	return "FlatFiles" + System.getProperty("file.separator");
    }
    
    /**
     * Combines the current and next directory and directory/file.
     * If second is a directory, end with a file separator
     * 
     * @param first
     * @param second
     * @return
     */
    public static String pathAppenders(String first, String second, boolean isDirectory)
    {
	String combinedDir = first;
	
	// Make the directory end with a file separator
	if (! first.endsWith(System.getProperty("file.separator")))
	{
	    combinedDir = combinedDir + System.getProperty("file.separator");
	}
	
	// Add the second thing on
	combinedDir = combinedDir + second;
	
	// Make a directory end with a file separator
	if (isDirectory)
	{
	    combinedDir = combinedDir + System.getProperty("file.separator");
	}
	
	return combinedDir;
    }
}
